package com.atguigu.gulimall.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.config.AliyunOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class OssController {
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunOssProperties properties;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @RequestMapping("/oss/policy")
    public R OssPolicy() {
       // System.out.println("**************"+aliyunOss.getAccessKeyId());
        String bucket = "mall--product"; // 请填写您的 bucketname 。
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        // String callbackUrl = "http://88.88.88.88:8888";
        //String dir = "user-dir-prefix/"; // 用户上传文件时指定的前缀。

        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = time + "/"; // 用户上传文件时指定的前缀。
        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return R.ok().put("data", respMap);
    }



//    @ApiOperation(value = "文件上传")
//    @PostMapping("upload")
//    public String upload(
//            @ApiParam(name = "file", value = "文件", required = true)
//            @RequestParam("file") MultipartFile file) {
//
//        //获取阿里云存储相关常量
//        String endPoint = properties.getEndpoint();
//        String accessKeyId = properties.getAccessKeyId();
//        String accessKeySecret = properties.getAccessKeySecret();
//        String bucketName = properties.getBucket();
//        String fileHost = "mall--product.oss-cn-beijing.aliyuncs.com";
//
//        String uploadUrl = null;
//
//        try {
//            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
//            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
//            if (!ossClient.doesBucketExist(bucketName)) {
//                //创建bucket
//                ossClient.createBucket(bucketName);
//                //设置oss实例的访问权限：公共读
//                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
//            }
//
//            //获取上传文件流
//            InputStream inputStream = file.getInputStream();
//
//            //构建日期路径：avatar/2019/02/26/文件名
//            String filePath = new DateTime().toString("yyyy/MM/dd");
//
//            //文件名：uuid.扩展名
//            String original = file.getOriginalFilename();
//            String fileName = UUID.randomUUID().toString();
//            String fileType = original.substring(original.lastIndexOf("."));
//            String newName = fileName + fileType;
//            String fileUrl = /*fileHost + "/" +*/ filePath + "/" + newName;
//
//            //文件上传至阿里云
//            ossClient.putObject(bucketName, fileUrl, inputStream);
//
//            // 关闭OSSClient。
//            ossClient.shutdown();
//
//            //获取url地址
//            uploadUrl = "http://" + bucketName + "." + endPoint + "/" + fileUrl;
//
//        } catch (IOException e) {
//
//        }
//        System.out.println(uploadUrl);
//        //返回r对象
//        return  uploadUrl;
//
//    }



}
